package mblog.web.controller.weibo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import mblog.base.utils.WeiBoUtils;
import mblog.core.persist.service.WeiBoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * Project  : mblog
 * Author   : Wu Tian Qiang
 * Date     : 2016/8/1
 */
@Controller
@RequestMapping(value = "/weibo")
public class WeiBoController {

    @Autowired
    private WeiBoService weiBoService;

    @RequestMapping(value = "/service")
    @ResponseBody
    private String doService(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String nonce = request.getParameter("nonce");
        String echoStr = request.getParameter("echostr");
        String timestamp = request.getParameter("timestamp");
        String signature = request.getParameter("signature");

        String returnContent = ""; //返回的响应结果。默认为空字符串。
        //验证签名
        boolean isValid = WeiBoUtils.vlidateSHA(signature, nonce, timestamp);
        if (isValid) { //签名正确时，如果存在echoStr就返回echoStr，否则接收数据
            if (StringUtils.isNotBlank(echoStr)) {
                //存在echoStr，是首次配置时验证url可达性。
                returnContent = echoStr; //返回内容为echoStr的内容
            } else {
                //正常推送消息时不会存在echoStr参数。
                //接收post过来的消息数据
                StringBuilder sb = new StringBuilder();
                BufferedReader in = request.getReader();
                String line;
                while ((line = in.readLine()) != null) {
                    sb.append(line);
                }
                //TODO 根据业务对消息进行处理。处理完成可以返回空串，也可以返回回复消息。
                System.out.println("received message : " + sb.toString());
//                received message : {"type":"event","receiver_id":3943559585,"sender_id":5584661780,"created_at":"Tue Aug 02 20:35:42 +0800 2016","text":"取消关注事件消息","data":{"subtype":"unfollow"}}

                JSONObject message = JSON.parseObject(sb.toString());
                String messageType = message.getString("type");
                switch (messageType) {
                    case "event":
                        returnContent = weiBoService.handleEvent(message);
                        break;
                }
            }
        } else {
            //TODO 异常信息
            returnContent = "sign error!";
        }

        return returnContent;
    }

}
